package com.wsjj.yjh.window;

import com.wsjj.yjh.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class WindowAggregateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        env.enableCheckpointing(2000, CheckpointingMode.EXACTLY_ONCE);
        DataStreamSource<String> source = env.socketTextStream("hadoop102", 7777);
        SingleOutputStreamOperator<WaterSensor> map = source.map(value -> {
            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
        });
        KeyedStream<WaterSensor, String> stream = map.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor value) throws Exception {
                return value.id;
            }
        });
        WindowedStream<WaterSensor, String, TimeWindow> window = stream.window(TumblingProcessingTimeWindows.of(Time.seconds(2L)));

        SingleOutputStreamOperator<String> aggregate = window.aggregate(new AggregateFunction<WaterSensor, Integer, String>() {
//         创建累加器   初始化累加器
            @Override
            public Integer createAccumulator() {
                System.out.println("创建累加器");
                return 0;
            }
//            计算存储，聚合逻辑
            @Override
            public Integer add(WaterSensor value, Integer accumulator) {
                System.out.println("调用add方法，value=" + value);
                return accumulator + value.getVc();
            }
//            获取最终结果，窗口触发时输出
            @Override
            public String getResult(Integer accumulator) {
                System.out.println("调用getResult方法");
                return accumulator.toString();
            }
//            只有会话窗口才会用到（一般用前三个）
            @Override
            public Integer merge(Integer a, Integer b) {
                System.out.println("调用merge方法 ");
                return null;
            }
        });
        aggregate.print();
        env.execute();
    }
}
